package sk.atletis.atletika;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.ContentValues;
import android.content.Context;

public class JsonHandler 
{
	private Context ctx;
	private String url;
	
	// Constructor
	public JsonHandler(Context ctx, String url) 
	{
		this.ctx = ctx;
		this.url = url;
	}
	
	public int updateCompetitions()
	{
		try
		{
			// Get string data
			String textData = getStringData();
			if (textData != null)
			{
				// Get JSON data
				JSONArray jsonData = new JSONArray(textData);
				if (jsonData != null)
				{
					
					// Get ContentValue
					JsonParser parser = new JsonParser(jsonData);
					ContentValues[] values = parser.parseCompetitions();
					if (values != null)
					{
						// Save ContentValues
						return ctx.getContentResolver().bulkInsert(CompetitionsContract.CONTENT_URI_COMPETITIONS, values);
					}
				}
			}
		}
		catch (JSONException e) { }
		
		return 0;
	}
	
	public int updateArticles() 
	{
		try	
		{
			// Get string data
			String textData = getStringData();
			if (textData != null)
			{
				// Get JSON data
				JSONArray jsonData = new JSONArray(textData);
				if (jsonData != null)
				{
					
					// Get ContentValue
					JsonParser parser = new JsonParser(jsonData);
					ContentValues[] values = parser.parseArticles();
					if (values != null)
					{
						// Save ContentValues
						return ctx.getContentResolver().bulkInsert(ArticlesContract.CONTENT_URI_ARTICLES, values);
					}
				}
			}
		}
		catch (JSONException e) { }
		
		return 0;
	}
	
	// Downloads string data from web, returns string
	private String getStringData()
	{
		String json = null;
		try 
		{
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpGet get = new HttpGet(url);

			HttpResponse httpResponse = httpClient.execute(get);
			HttpEntity httpEntity = httpResponse.getEntity();
			json = EntityUtils.toString(httpEntity);

			return json;
		} 
		catch (UnsupportedEncodingException e) { } 
		catch (ClientProtocolException e) { } 
		catch (IOException e) { }
		
		return null;
	}
	
	
	
	
	
}
